package com.wenju.wjvideoplay.util;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.net.Uri;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.widget.AdapterView;
import android.widget.Toast;

import com.ksyun.media.player.IMediaPlayer;
import com.ksyun.media.player.KSYMediaPlayer;
import com.wenju.wjvideoplay.CloudCameraHistoryPlaybackActivity;
import com.wenju.wjvideoplay.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class WenMediaPlayerUtil {
    private KSYMediaPlayer firstPlayer,
            nextMediaPlayer; //一段视频播放结束后，播放下一段视频
    private Surface mSurface;
    private Context mContext;
    //准备播放视频
    private Boolean isReadyPlay = false;
    //视频播放结束
    private Boolean isEndPlay = false;
    //存放所有视频端的url
    private ArrayList<String> mVideoListQueue;
    //所有player对象的缓存
    private HashMap<String, KSYMediaPlayer> playersCache = new HashMap<>();
    //当前播放视频
    private int currentVideoIndex = 0;
    private int cacheVideoIndex = 0;
    private Timer mBufferTimer;
    private static onWjSurfaceTextureAvailable mWjSurfaceTextureAvailable;

    public WenMediaPlayerUtil(Context context) {
        this.mContext = context;
    }

    public void setTextureView(TextureView textureView) {
        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                mSurface = new Surface(surface);
                if (mWjSurfaceTextureAvailable != null) {
                    mWjSurfaceTextureAvailable.onWjSurfaceTextureAvailable();
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {


            }
        });
    }

    //监听Surface初始化状态
    public interface onWjSurfaceTextureAvailable {
        void onWjSurfaceTextureAvailable();
    }
    public void setWjSurfaceTextureAvailable(onWjSurfaceTextureAvailable listener) {
        mWjSurfaceTextureAvailable = listener;
    }


    /**
     * 播放首段视频的player,异步加载,准备好之后才进行播放，否则出现界面卡顿
     *
     * @param mVideoPlayTime 播放时间
     */
    public void initFirstPlayer(final int mVideoPlayTime, ArrayList<String> VideoListQueue) {
        playersCache.clear();
        if (mBufferTimer != null) {
            mBufferTimer.cancel();
        }

        this.mVideoListQueue = VideoListQueue;
        try {
            firstPlayer = new KSYMediaPlayer.Builder(mContext).build();
            firstPlayer.setSurface(mSurface);
            Uri uri = Uri.parse(mVideoListQueue.get(currentVideoIndex));
            firstPlayer.setDataSource(mContext, uri);
            //限制流量大小，该值较大延迟较大,该值较小,则对网络波动更敏感,容易引发卡顿
            firstPlayer.setBufferTimeMax(1f);
            firstPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        firstPlayer.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer mp) {
                //准备播放
                mp.start();
                mp.seekTo(mVideoPlayTime);
                getHttpBufferSize();
                isReadyPlay = true;
            }
        });

        firstPlayer.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer mp) {
                //第一个视频源播放结束
                Log.d("----------->", "第一个播放完毕");
                onVideoPlayCompleted(mp);
            }
        });
    }

    private void initNexttPlayer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("初始化视频------》", "初始化视频");
                Log.d("currentVideoIndex-->", currentVideoIndex + "");
                nextMediaPlayer = new KSYMediaPlayer.Builder(mContext).build();
                try {
                    if (currentVideoIndex < mVideoListQueue.size() - 1) {
                        nextMediaPlayer.setDataSource(mVideoListQueue.get(currentVideoIndex + 1));
                    }
                    if (nextMediaPlayer != null) {
                        nextMediaPlayer.shouldAutoPlay(false);
                        nextMediaPlayer.prepareAsync();
                    }
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //存储下一个缓存播放器
                playersCache.put(String.valueOf(currentVideoIndex), nextMediaPlayer);

                if (nextMediaPlayer != null) {
                    nextMediaPlayer.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(IMediaPlayer mp) {
                            Log.d("----------->", "下一个播放完毕");
                            onVideoPlayCompleted(mp);
                        }
                    });
                }

            }
        }).start();
    }

    /**
     * 负责处理一段视频播放过后，切换player播放下一段视频
     * @param mp 结束的MediaPlayer
     */
    private void onVideoPlayCompleted(IMediaPlayer mp) {
        mp.setDisplay(null);
        Log.d("playersCache----->", playersCache.size() + "");
        Log.d("cacheVideoIndex----->", cacheVideoIndex + "");
        firstPlayer = playersCache.get(String.valueOf(currentVideoIndex));
        ++cacheVideoIndex;
        ++currentVideoIndex;
        Log.d("firstPlayer----->", firstPlayer + "");
        if (firstPlayer != null) {
            try {
                firstPlayer.setSurface(mSurface);
                firstPlayer.setBufferTimeMax(1f);
                if (CloudCameraHistoryPlaybackActivity.getIsSound()) {
                    firstPlayer.setVolume(0, 0);
                } else {
                    firstPlayer.setVolume(1, 1);
                }
                firstPlayer.start();
            } catch (IllegalStateException ignored) {

            }
        } else {
            isReadyPlay = false;
            isEndPlay = true;
            Toast.makeText(mContext, mContext.getString(R.string.video_final), Toast.LENGTH_SHORT).show();
        }
    }


    // 界面销毁时释放所有资源
    public void onDestoryMediaplayer() {
        if (firstPlayer != null) {
            firstPlayer.stop();
            firstPlayer.release();
            firstPlayer = null;
        }
        if (nextMediaPlayer != null) {
            try {
                nextMediaPlayer.stop();
            } catch (IllegalStateException ignored) {
                Log.e("IllegalStateException", ignored.toString());
            }
            nextMediaPlayer.release();
            nextMediaPlayer = null;
        }
        currentVideoIndex = 0;
        isReadyPlay = false;
        isEndPlay = false;

        if (mBufferTimer != null) {
            mBufferTimer.cancel();
        }
    }

    //当前播放视频段
    public int getMediaPlayerIndex() {
        return currentVideoIndex;
    }

    //设置视频播放段
    public void setMediaPlayerIndex(int currentVideoIndex) {
        this.currentVideoIndex = currentVideoIndex;
    }

    //当前视频播放器
    public KSYMediaPlayer getMediaPlayer() {
        return firstPlayer;
    }

    //是否准备播放
    public Boolean getIsReadyPlay() {
        return isReadyPlay;
    }

    //视频是否播放结束
    public Boolean getIsEndPlay() {
        return isEndPlay;
    }


    //判断是否有添加过初始化视频
    private boolean isFirst;

    private void getHttpBufferSize() {
        mBufferTimer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (firstPlayer != null) {
                    try {
                        if (firstPlayer.getDuration() != 0) {
                            if ((firstPlayer.getCurrentPosition() * 100 / firstPlayer.getDuration()) > 60) {
                                if (isFirst) {
                                    initNexttPlayer();
                                    isFirst = false;
                                }
                            } else {
                                isFirst = true;
                            }
                        }
                    } catch (IllegalStateException ignored) {
                        Log.e("IllegalStateException", ignored.toString());
                    }
                }
            }
        };
        mBufferTimer.schedule(task, 0, 1000);//0秒后执行，每隔1s执行一次
    }
}
